<template>
  <div class="container">
    <van-nav-bar
      fixed
      left-arrow
      @click-left="$router.back()"
      title="小思同学"
    ></van-nav-bar>

    <div class="chat-list">
      <div v-for="(item, index) in list" :key="index">
        <div class="chat-item left" v-if="item.name === 'xs'">
          <van-image
            fit="cover"
            round
            src="https://img.yzcdn.cn/vant/cat.jpeg"
          />
          <div class="chat-pao">{{ item.msg }}</div>
        </div>
        <div class="chat-item right" v-else>
          <div class="chat-pao">{{ item.msg }}</div>
          <van-image fit="cover" round :src="$store.state.userInfo.photo" />
        </div>
      </div>
    </div>

    <!-- 对话区域 -->
    <div class="reply-container van-hairline--top">
      <van-field
        v-model.trim="word"
        v-on:keyup.enter="send"
        placeholder="说点什么..."
      >
        <template #button>
          <span @click="send" style="font-size: 24px; color: #999">提交</span>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
import { io } from 'socket.io-client'
let socket = null
export default {
  name: 'Chat',
  data() {
    return {
      word: '',
      list: []
    }
  },
  created() {
    // 调用 io 方法，创建 websocket 连接
    socket = io('ws://www.liulongbin.top:9999')

    // 为 socket 连接对象，绑定 connnect 事件
    socket.on('connect', () => {
      console.log('websocket服务器连接成功')
    })
    // 为 socket 连接对象，绑定 message 事件
    socket.on('message', (msg) => {
      console.log('msg:', msg)
      // 把机器人发送过来的消息，push 到 list 数组中
      this.list.push({ name: 'xs', msg })
    })
    socket.on('disconnect', () => {
      console.log('websocket服务器断开连接')
    })
  },

  components: {},

  computed: {},

  mounted() {},
  beforeDestroy() {
    // 关闭连接
    socket.close()
    // 释放内存（销毁 socket 实例对象）
    // 垃圾回收机制
    socket = null
  },

  methods: {
    send() {
      if (this.word.length < 1) {
        return this.$notify({ type: 'warning', message: '聊天信息不能为空' })
      }
      // 前端往服务端发聊天信息
      socket.emit('send', this.word)
      // 将自己的聊天信息 放到数组里
      this.list.push({ name: 'me', msg: this.word })
      this.word = ''
    },
    gunToBottom() {
      const items = document.querySelectorAll('.chat-item')
      const lastItem = items[items.length - 1]
      lastItem.scrollIntoView({
        behavior: 'smooth',
        block: 'end'
      })
    }
  },
  watch: {
    list(value) {
      this.$nextTick(() => {
        this.gunToBottom()
      })
    }
  }
}
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  background: #fafafa;
  padding: 92px 0 100px 0;
  .chat-list {
    height: 100%;
    overflow-y: scroll;
    .chat-item {
      padding: 20px;
      .van-image {
        vertical-align: top;
        width: 80px;
        height: 80px;
      }
      .chat-pao {
        vertical-align: top;
        display: inline-block;
        min-width: 80px;
        max-width: 70%;
        min-height: 80px;
        line-height: 76px;
        border: 0.5px solid #c2d9ea;
        border-radius: 8px;
        position: relative;
        padding: 0 20px;
        background-color: #e0effb;
        word-break: break-all;
        font-size: 28px;
        color: #333;
        &::before {
          content: '';
          width: 20px;
          height: 20px;
          position: absolute;
          top: 24px;
          border-top: 0.5px solid #c2d9ea;
          border-right: 0.5px solid #c2d9ea;
          background: #e0effb;
        }
      }
    }
  }
}
.chat-item.right {
  text-align: right;
  .chat-pao {
    margin-left: 0;
    margin-right: 30px;
    &::before {
      right: -12px;
      transform: rotate(45deg);
    }
  }
}
.chat-item.left {
  text-align: left;
  .chat-pao {
    margin-left: 30px;
    margin-right: 0;
    &::before {
      left: -10px;
      transform: rotate(-135deg);
    }
  }
}
.reply-container {
  position: fixed;
  left: 0;
  bottom: 0;
  height: 88px;
  width: 100%;
  background: #f5f5f5;
  z-index: 9999;
}
</style>
